﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inspired.Euler
{
    /// <summary>
    /// The number 3797 has an interesting property. Being prime itself, it is possible to continuously 
    /// remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. 
    /// 
    /// Similarly we can work from right to left: 3797, 379, 37, and 3.
    /// 
    /// Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
    /// 
    /// NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
    /// </summary>
    public static class Problem037
    {
        /// <summary>
        /// Find the sum of all eleven primes that are both truncatable from left to right and right to left.
        /// </summary>
        [EulerProblem(37, Title = "Find the sum of all eleven primes that are both truncatable from left to right and right to left.")]
        public static long Solve()
        {
            return Extensions.GetPrimes()
                .Where(prime => prime.IsTruncatable())
                .Take(11)
                //.Display()
                .Sum();
        }

        static bool IsTruncatable(this long prime)
        {
            return
                prime > 7 &&
                prime.Truncate().All(t1 => t1.IsPrime());
        }

        // 1 = left to right, 2 = right to left
    static IEnumerable<long> Truncate(this long number)
    {
        yield return number;

        // 3797, 379, 37, 3, 797, 97, 7
        int i = 10;
        while (number / i > 0)
        {
            yield return number / i;
            yield return number % i;
            i *= 10;
        }

            //long aux = number;
            //while ((aux /= 10) > 0) // right to left
            //    yield return aux;

            //while ((number = (number.Reverse() / 10).Reverse()) > 0) // left to right
            //{
            //    yield return number;
            //}
        }
    }
}
